import 'package:flutter/foundation.dart';
import 'activity_provider.dart';
import 'exhibition_provider.dart';
import 'education_provider.dart';
import 'community_provider.dart';

// 应用主状态管理类
class AppProvider with ChangeNotifier {
  late final ActivityProvider _activityProvider;
  late final ExhibitionProvider _exhibitionProvider;
  late final EducationProvider _educationProvider;
  late final CommunityProvider _communityProvider;
  
  bool _isInitialized = false;
  String? _globalError;
  
  // 用户相关状态
  String? _currentUserId;
  Map<String, dynamic> _userPreferences = {};
  
  // 应用设置
  bool _isDarkMode = false;
  String _language = 'zh_CN';
  bool _notificationsEnabled = true;
  
  AppProvider() {
    _initializeProviders();
  }
  
  // Getters
  ActivityProvider get activityProvider => _activityProvider;
  ExhibitionProvider get exhibitionProvider => _exhibitionProvider;
  EducationProvider get educationProvider => _educationProvider;
  CommunityProvider get communityProvider => _communityProvider;
  
  bool get isInitialized => _isInitialized;
  String? get globalError => _globalError;
  String? get currentUserId => _currentUserId;
  Map<String, dynamic> get userPreferences => _userPreferences;
  bool get isDarkMode => _isDarkMode;
  String get language => _language;
  bool get notificationsEnabled => _notificationsEnabled;
  
  void _initializeProviders() {
    _activityProvider = ActivityProvider();
    _exhibitionProvider = ExhibitionProvider();
    _educationProvider = EducationProvider();
    _communityProvider = CommunityProvider();
    
    // 监听各个provider的变化
    _activityProvider.addListener(_onProviderChanged);
    _exhibitionProvider.addListener(_onProviderChanged);
    _educationProvider.addListener(_onProviderChanged);
    _communityProvider.addListener(_onProviderChanged);
    
    _loadUserData();
    _isInitialized = true;
    notifyListeners();
  }
  
  void _onProviderChanged() {
    // 当子provider发生变化时，可以在这里处理全局逻辑
    notifyListeners();
  }
  
  Future<void> _loadUserData() async {
    try {
      // 模拟加载用户数据
      await Future.delayed(const Duration(milliseconds: 500));
      
      _currentUserId = 'user_1'; // 模拟当前用户ID
      _userPreferences = {
        'favoriteCategories': ['书法', '茶艺', '国画'],
        'learningGoals': ['提高书法水平', '学习茶艺表演'],
        'participationLevel': 'active',
        'joinDate': DateTime.now().subtract(const Duration(days: 365)).toIso8601String(),
      };
      
      notifyListeners();
    } catch (e) {
      _globalError = '加载用户数据失败: $e';
      notifyListeners();
    }
  }
  
  // 用户认证相关
  Future<bool> login(String username, String password) async {
    try {
      // 模拟登录过程
      await Future.delayed(const Duration(seconds: 1));
      
      if (username.isNotEmpty && password.isNotEmpty) {
        _currentUserId = 'user_${username.hashCode}';
        await _loadUserData();
        return true;
      }
      return false;
    } catch (e) {
      _globalError = '登录失败: $e';
      notifyListeners();
      return false;
    }
  }
  
  Future<void> logout() async {
    try {
      _currentUserId = null;
      _userPreferences.clear();
      
      // 清除各个provider的用户相关数据
      await _activityProvider.refresh();
      await _exhibitionProvider.refresh();
      await _educationProvider.refresh();
      await _communityProvider.refresh();
      
      notifyListeners();
    } catch (e) {
      _globalError = '登出失败: $e';
      notifyListeners();
    }
  }
  
  // 应用设置
  void setDarkMode(bool isDark) {
    _isDarkMode = isDark;
    _saveSettings();
    notifyListeners();
  }
  
  void setLanguage(String language) {
    _language = language;
    _saveSettings();
    notifyListeners();
  }
  
  void setNotificationsEnabled(bool enabled) {
    _notificationsEnabled = enabled;
    _saveSettings();
    notifyListeners();
  }
  
  Future<void> _saveSettings() async {
    // 模拟保存设置到本地存储
    await Future.delayed(const Duration(milliseconds: 100));
  }
  
  // 用户偏好设置
  void updateUserPreference(String key, dynamic value) {
    _userPreferences[key] = value;
    notifyListeners();
  }
  
  T? getUserPreference<T>(String key) {
    return _userPreferences[key] as T?;
  }
  
  // 全局搜索
  Future<Map<String, List<dynamic>>> globalSearch(String query) async {
    if (query.isEmpty) return {};
    
    try {
      final results = <String, List<dynamic>>{};
      
      // 搜索活动
      _activityProvider.setSearchQuery(query);
      results['activities'] = _activityProvider.filteredActivities.take(5).toList();
      
      // 搜索展览
      _exhibitionProvider.setSearchQuery(query);
      results['exhibitions'] = _exhibitionProvider.filteredExhibitions.take(5).toList();
      
      // 搜索课程
      _educationProvider.setSearchQuery(query);
      results['courses'] = _educationProvider.filteredCourses.take(5).toList();
      
      // 搜索社区帖子
      _communityProvider.setSearchQuery(query);
      results['posts'] = _communityProvider.filteredPosts.take(5).toList();
      
      return results;
    } catch (e) {
      _globalError = '搜索失败: $e';
      notifyListeners();
      return {};
    }
  }
  
  // 获取用户活动统计
  Map<String, dynamic> getUserActivityStats() {
    if (_currentUserId == null) return {};
    
    final activityStats = _activityProvider.getUserStats(_currentUserId!);
    final exhibitionStats = _exhibitionProvider.getUserStats(_currentUserId!);
    final educationStats = _educationProvider.getUserStats(_currentUserId!);
    final communityStats = _communityProvider.getUserStats(_currentUserId!);
    
    return {
      'activities': activityStats,
      'exhibitions': exhibitionStats,
      'education': educationStats,
      'community': communityStats,
      'totalParticipations': 
          (activityStats['registeredCount'] ?? 0) +
          (exhibitionStats['bookedCount'] ?? 0) +
          (educationStats['enrolledCount'] ?? 0),
      'totalContributions': 
          (communityStats['postCount'] ?? 0) +
          (communityStats['totalComments'] ?? 0),
    };
  }
  
  // 获取个性化推荐
  Map<String, List<dynamic>> getPersonalizedRecommendations() {
    final recommendations = <String, List<dynamic>>{};
    
    // 基于用户偏好推荐活动
    final favoriteCategories = getUserPreference<List<String>>('favoriteCategories') ?? [];
    if (favoriteCategories.isNotEmpty) {
      recommendations['activities'] = _activityProvider.getRecommendedActivities(limit: 3);
      recommendations['exhibitions'] = _exhibitionProvider.getRecommendedExhibitions(limit: 3);
      recommendations['courses'] = _educationProvider.getRecommendedCourses(limit: 3);
      recommendations['posts'] = _communityProvider.getRecommendedPosts(limit: 3);
    }
    
    return recommendations;
  }
  
  // 获取热门内容
  Map<String, List<dynamic>> getPopularContent() {
    return {
      'activities': _activityProvider.getRecommendedActivities(limit: 5),
      'exhibitions': _exhibitionProvider.getRecommendedExhibitions(limit: 5),
      'courses': _educationProvider.getRecommendedCourses(limit: 5),
      'posts': _communityProvider.filteredPosts.where((p) => p.isHot).take(5).toList(),
    };
  }
  
  // 获取最新内容
  Map<String, List<dynamic>> getLatestContent() {
    return {
      'activities': _activityProvider.filteredActivities.take(5).toList(),
      'exhibitions': _exhibitionProvider.getUpcomingExhibitions().take(5).toList(),
      'courses': _educationProvider.filteredCourses.take(5).toList(),
      'posts': _communityProvider.filteredPosts.take(5).toList(),
    };
  }
  
  // 刷新所有数据
  Future<void> refreshAll() async {
    try {
      await Future.wait([
        _activityProvider.refresh(),
        _exhibitionProvider.refresh(),
        _educationProvider.refresh(),
        _communityProvider.refresh(),
      ]);
      
      await _loadUserData();
    } catch (e) {
      _globalError = '刷新数据失败: $e';
      notifyListeners();
    }
  }
  
  // 清除全局错误
  void clearGlobalError() {
    _globalError = null;
    notifyListeners();
  }
  
  // 获取应用统计信息
  Map<String, dynamic> getAppStats() {
    return {
      'totalActivities': _activityProvider.activities.length,
      'totalExhibitions': _exhibitionProvider.exhibitions.length,
      'totalCourses': _educationProvider.courses.length,
      'totalPosts': _communityProvider.posts.length,
      'totalUsers': _communityProvider.users.length,
      'activeUsers': _communityProvider.users.where((u) => 
          DateTime.now().difference(u.joinDate).inDays < 30).length,
    };
  }
  
  @override
  void dispose() {
    _activityProvider.removeListener(_onProviderChanged);
    _exhibitionProvider.removeListener(_onProviderChanged);
    _educationProvider.removeListener(_onProviderChanged);
    _communityProvider.removeListener(_onProviderChanged);
    
    _activityProvider.dispose();
    _exhibitionProvider.dispose();
    _educationProvider.dispose();
    _communityProvider.dispose();
    
    super.dispose();
  }
}